from flask import Blueprint, render_template, jsonify, redirect, url_for, session, make_response
from exts import db
# from flask_mail import Message
from flask import request
import string
import random
# from models import EmailCaptchaModel
from .forms import RegisterForm, LoginForm, ForgotForm
from models import UserModel, ForgotEmailModel
from werkzeug.security import generate_password_hash, check_password_hash
from decorators import login_required
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from datetime import timedelta


# /auth
bp = Blueprint("auth", __name__, url_prefix="/auth")


@bp.route("/login", methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return jsonify({'success': False})
    else:
        form = LoginForm(request.form)
        if form.validate():
            email = form.email.data
            password = form.password.data
            print(email, password)
            user = UserModel.query.filter_by(email=email).first()
            if not user:
                print("邮箱在数据库中不存在！")
                return jsonify({'success': False, 'message': "账号不存在！"})
            if check_password_hash(user.password, password):
                
                # return response
                access_token = create_access_token(identity=email, expires_delta=timedelta(hours=10))
                # print(access_token)
                return jsonify({"access_token": access_token, "username": user.username, "email": user.email}), 200
                
                # return jsonify({'success': True, 'email': email})
            else:
                print("密码错误！")
                return jsonify({'success': False, 'message': "密码错误！"})
        else:
            print("[+]", form.errors)
            error_info = ""
            for i,j in form.errors.items():
                error_info = error_info + j[0] + " "
            return jsonify({'success': False, 'message': error_info})


# GET：从服务器上获取数据
# POST：将客户端的数据提交给服务器
@bp.route("/register", methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return jsonify({'success': False})
    else:
        # 验证用户提交的邮箱和验证码是否对应且正确
        # 表单验证：flask-wtf: wtforms
        form = RegisterForm(request.form)
        # print(form.email.data, form.username.data, form.password.data, form.password_confirm.data)
        if form.validate():
            email = form.email.data
            username = form.username.data
            password = form.password.data 
            user = UserModel(email=email, username=username, password=generate_password_hash(password))
            db.session.add(user)
            db.session.commit()
            # return redirect(url_for("auth.login"))
            return jsonify({'success': True})
        else:
            print("[+]", form.errors)
            error_info = ""
            for i,j in form.errors.items():
                error_info = error_info + j[0] + " "
            return jsonify({'success': False, 'message': error_info})
        
        
@bp.route("/forgotpassword", methods=['GET', 'POST'])
def forgotpassword():
    if request.method == 'GET':
        return jsonify({'success': False})
    else:
        form = ForgotForm(request.form)
        
        if form.validate():
            email = form.email.data
            user = UserModel.query.filter_by(email=email).first()
            if not user:
                print("邮箱在数据库中不存在！")
                return jsonify({'success': False, 'message': "账号不存在！"})
            else:
                user = ForgotEmailModel(email=email)
                db.session.add(user)
                db.session.commit()
                return jsonify({'success': True})
        else:
            print("[+]", form.errors)
            error_info = ""
            for i,j in form.errors.items():
                error_info = error_info + j[0] + " "
            return jsonify({'success': False, 'message': error_info})


@bp.route("/logout")
def logout():
    session.clear()
    return redirect("/")


@bp.route("/setting/delete")
@login_required
def delete_user():
    user_id = session.get("user_id")
    user = UserModel.query.get(user_id)
    db.session.delete(user)
    db.session.commit()
    session.clear()
    return redirect("/")


# # bp.route：如果没有指定methods参数，默认就是GET请求
# @bp.route("/captcha/email")
# def get_email_captcha():
#     # /captcha/email/<email>
#     # /captcha/email?email=xxx@qq.com
#     email = request.args.get("email")
#     # 4/6：随机数组、字母、数组和字母的组合
#     source = string.digits*4
#     captcha = random.sample(source, 4)
#     captcha = "".join(captcha)
#     # I/O：Input/Output
#     message = Message(subject="知了传课注册验证码", recipients=[email], body=f"您的验证码是:{captcha}")
#     mail.send(message)
#     # memcached/redis
#     # 用数据库表的方式存储
#     email_captcha = EmailCaptchaModel(email=email,captcha=captcha)
#     db.session.add(email_captcha)
#     db.session.commit()
#     # RESTful API
#     # {code: 200/400/500, message: "", data: {}}
#     return jsonify({"code": 200, "message": "", "data": None})


# @bp.route("/mail/test")
# def mail_test():
#     message = Message(subject="邮箱测试", recipients=["2561884482@qq.com"], body="这是一条测试邮件")
#     mail.send(message)
#     return "邮件发送成功！"